define (require)->


    template = require "text!post/template/post_input.handlebars"
    FileAdapter = require "post/FileAdapter"

    Backbone.View.extend

        template: Handlebars.compile(template)

        events:
            "click .virtual": "_toInput"
            "click .close": "_closeInput"
            "click button": "_submit"
            "click .tags-bar": "_focusIunput"
            "keydown .tags-bar input": "_removeTag"
            "keyup .tags-bar input": "_inputTag"

        initialize: (options)->
            @$boforeArr = []
            @newCollection = options.newCollection

        _toInput: (e)->
            @$(".virtual").addClass("out")
            @$(".real").fadeIn()

        _closeInput: (e)->
            self.$(".virtual").removeClass("out")
            self.$(".real").fadeOut()


        _submit: (e)->
            self = @
            model = new @collection.model({
                content: @$("textarea").val() || @$(".attach-one").data("name")
                tags: @$boforeArr.map(($tag)-> return $tag.text())
                attach: @$(".attach-one").data("id")
            })
            model.create((response)->
                self.newCollection.add(response)
                self._empty()
                self._closeInput();
            )

        _focusIunput: (e)->
            @$("input.tags").focus()

        _inputTag: (e) ->
            console.log(e.keyCode)
            if(e.keyCode == 13)
                $tag = $("<span class='tag'>##{$(e.target).val()}</span>")
                @$boforeArr.push($tag)
                $(e.target).before($tag)
                $(e.target).val("")

            if(e.keyCode == 188 || e.keyCode == 32)
                $tag = $("<span class='tag'>##{$(e.target).val().replace(",","")}</span>")
                @$boforeArr.push($tag)
                $(e.target).before($tag)
                $(e.target).val("")

            $(e.target).focus()

        _removeTag: (e)->
            if(e.keyCode == 8 && $(e.target).val() == "")
                @$boforeArr.pop().remove()


        _empty: ()->
            @$("textarea").val("")
            @$("input.tags").val("")
            @$(".attach").empty().hide();
            while(@.$boforeArr.length > 0)
                @.$boforeArr.pop().remove()

        _bindDrop: (holder)->
            self = @
            holder.ondragover = -> false
            holder.ondragend = -> false
            holder.ondrop = (evt) ->
                self._toInput()
                self.$(".attach").show()
                FileAdapter[if FileAdapter[file.type] then file.type else "text/plain"](file, self.$(".attach")) for file in evt.dataTransfer.files
                return false


        render: ()->
            $html = $(@template(@model.toJSON()))
            @setElement($html)
            @_bindDrop(@$("textarea")[0])
            @_bindDrop(@$(".virtual")[0])
            @